# 文件上传 File, UploadFile

from typing import Annotated

from fastapi import FastAPI, File, Form, UploadFile

app = FastAPI()


# 小文件不处理时 bytes
@app.post("/files/")
async def create_file(file: Annotated[bytes, File()]):
    return {"file_size": len(file)}


# 大文件流式处理 UploadFile
@app.post("/uploadfile/")
async def create_upload_file(
        file: Annotated[UploadFile, File()],
):
    return {"filename": file.filename}


# 多文件上传
@app.post("/uploadfiles/")
async def create_upload_files(files: list[UploadFile]):
    return {"filenames": [file.filename for file in files]}


# 多文件上传并保存
@app.post("/upload-files/")
async def upload_files(files: list[UploadFile] = File(...)):
    file_names = []
    for file in files:
        contents = await file.read()
        with open(file.filename, "wb") as f:
            f.write(contents)
        file_names.append(file.filename)
    return {"file_names": file_names}


# 多文件上传 还带其他参数 引入Form 如果没有什么特殊校验的话，不用 Annotated，也可以不写模型
@app.post("/upload/")
async def upload(
        big_file: UploadFile = File(), # 必传
        name: str = Form(...), # ... 必传
        description: str = Form(None) # None可不传
):
    contents = await big_file.read()
    with open(big_file.filename, "wb") as f:
        f.write(contents)

    return {
        "name": name,
        "description": description,
        "big_file_name": big_file.filename
    }
